/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.ProdCommDataDto;
import com.yami.shop.bean.app.dto.ProdCommDto;
import com.yami.shop.bean.app.dto.ProductDto;
import com.yami.shop.bean.event.GetLivingRoomEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.bean.model.SkuLang;
import com.yami.shop.bean.param.ProductParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.util.Json;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.delivery.comment.model.SameCity;
import com.yami.shop.delivery.comment.service.SameCityService;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.ProdCommService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SkuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/prod")
@Api(tags = "商品接口")
public class ProdController {

    @Autowired
    private ProductService prodService;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private SameCityService sameCityService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private SkuService skuService;

    @Autowired
    private ProdCommService prodCommService;



    @GetMapping("/prodInfo")
    @ApiOperation(value = "商品详情信息", notes = "根据商品ID（prodId）获取商品信息")
    @ApiImplicitParam(name = "prodId", value = "商品ID", required = true, dataType = "Long")
    public ResponseEntity<ProductDto> prodInfo(Long prodId) {
        Integer dbLang = I18nMessage.getDbLang();
        Product product = prodService.getProductByProdId(prodId, dbLang);
        if (product == null || product.getStatus() != 1) {
            // 商品已下线
            throw new YamiShopBindException("yami.product.off.shelves");
        }
        // 发送事件，获取商品可用的正在开播直播间
        applicationContext.publishEvent(new GetLivingRoomEvent(prodId,product));
        List<Sku> skuList = skuService.listByProdId(prodId, dbLang);
        // 将当前语言的prodName给sku
        for (Sku sku : skuList) {
            for (SkuLang skuLang : sku.getSkuLangList()) {
                if(Objects.equals(skuLang.getLang(),dbLang) && StrUtil.isNotBlank(skuLang.getProperties())){
                    sku.setProperties(skuLang.getProperties());
                }
            }
        }
        // 启用的sku列表
        List<Sku> useSkuList = skuList.stream().filter(sku -> sku.getStatus() == 1).collect(Collectors.toList());
        product.setSkuList(useSkuList);
        // 物流模板
        Product.DeliveryModeVO deliveryModeVO = Json.parseObject(product.getDeliveryMode(), Product.DeliveryModeVO.class);
        ProductDto productDto = mapperFacade.map(product, ProductDto.class);
        SameCity sameCity = sameCityService.getSameCityByShopId(product.getShopId());
        if(deliveryModeVO.getHasCityDelivery() != null && deliveryModeVO.getHasCityDelivery() && Objects.nonNull(sameCity)){
            productDto.setStartDeliveryFee(sameCity.getStartingFee());
        }
        productDto.setDeliveryModeVO(deliveryModeVO);
        return ResponseEntity.ok(productDto);
    }

    @GetMapping("/isStatus")
    @ApiOperation(value = "校验商品是否下架", notes = "根据商品ID（prodId）校验商品是否下架")
    @ApiImplicitParam(name = "prodId", value = "商品ID", required = true)
    public ResponseEntity<Boolean> isStatus(Long prodId) {
        Product product = prodService.getProductByProdId(prodId, I18nMessage.getDbLang());
        if (product == null || product.getStatus() != 1) {
            return ResponseEntity.ok(false);
        }
        return ResponseEntity.ok(true);
    }

    @GetMapping("/lastedProdPage")
    @ApiOperation(value = "新品推荐", notes = "获取新品推荐商品列表")
    @ApiImplicitParams({
    })
    public ResponseEntity<IPage<ProductDto>> lastedProdPage(PageParam<ProductDto> page) {
        IPage<ProductDto> productDtoIPage = prodService.pageByPutawayTime(page,I18nMessage.getDbLang());
        return ResponseEntity.ok(productDtoIPage);
    }

    /**
     * 获取商品信息
     */
    @GetMapping("/listProdByIdsAndType")
    @ApiOperation(value = "获取商品信息", notes = "根据商品ids获取商品信息")
    public ResponseEntity<List<Product>> listProdByIdsAndType(ProductParam product) {
        product.setLang(I18nMessage.getDbLang());
        List<Product> products = prodService.listProdByIdsAndType(product);
        return ResponseEntity.ok(products);
    }

    @GetMapping("/moreBuyProdList")
    @ApiOperation(value = "每日疯抢", notes = "获取销量最多的商品列表")
    @ApiImplicitParams({})
    public ResponseEntity<IPage<ProductDto>> moreBuyProdList(PageParam<ProductDto> page) {
        IPage<ProductDto> productDtoIPage = prodService.moreBuyProdList(page,I18nMessage.getDbLang());
        return ResponseEntity.ok(productDtoIPage);
    }

    @GetMapping("/discountProds")
    @ApiOperation(value = "根据活动id获取活动商品列表", notes = "根据活动id获取活动商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "discountId", value = "活动id", required = true, dataType = "Long"),
    })
    public ResponseEntity<IPage<ProductDto>> getDiscountProds(
            @RequestParam(value = "discountId", required = true) Long discountId,
            PageParam<ProductDto> page) {
        IPage<ProductDto> productDtoList = prodService.pageByDiscountId(page, discountId,I18nMessage.getDbLang());
        return ResponseEntity.ok(productDtoList);
    }

    @GetMapping("/prodCommData")
    @ApiOperation(value = "返回商品评论数据(好评率 好评数量 中评数 差评数)", notes = "根据商品id获取")
    public ResponseEntity<ProdCommDataDto> getProdCommData(Long prodId) {
        return ResponseEntity.ok(prodCommService.getProdCommDataByProdId(prodId));
    }


    @GetMapping("/prodCommPageByProd")
    @ApiOperation(value = "根据商品返回评论分页数据", notes = "传入商品id和页码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "prodId", value = "商品id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "evaluate", value = "-1或null 全部，0好评 1中评 2差评 3有图", required = true, dataType = "Long"),
    })
    public ResponseEntity<IPage<ProdCommDto>> getProdCommPageByProdId(PageParam page, Long prodId, Integer evaluate) {
        return ResponseEntity.ok(prodCommService.getProdCommDtoPageByProdId(page, prodId, evaluate));
    }

}
